﻿using System;
using EduFormManager.Models;
using EduFormManager.Models.Repo;

namespace EduFormManager.Forms.UserControls
{
    public partial class XtraDictionaryEditMunitControl : XtraBaseControl
    {
        private Municipality m_munit;
        private XtraDictionaryMunitControl m_munitControl;

        public XtraDictionaryEditMunitControl()
        {
            InitializeComponent();

            this.labelError.Text = string.Empty;

            Init();
        }

        public XtraDictionaryEditMunitControl(XtraDictionaryMunitControl parentMunitControl = null)
        {
            InitializeComponent();

            this.m_munitControl = parentMunitControl;

            Init();
        }

        private void Init()
        {
            this.labelError.Text = string.Empty;
            this.ControlType = Type.Component;
        }

        public override Type ControlType
        {
            get
            {
                return base._controlType;
            }
            set
            {
                this.buttonOk.Visible = (value == Type.Form);
                this.buttonCancel.Visible = (value == Type.Form);
                base._controlType = value;
            }
        }

        public XtraDictionaryMunitControl ParentMunitControl
        {
            set
            {
                this.m_munitControl = value;
            }
            get
            {
                return this.m_munitControl;
            }
        }

        public Municipality Municipality
        {
            set
            {
                if (value == null)
                    return;
                this.m_munit = value;

                this.textBoxDictMunitName.Text = m_munit.Name;
                this.textBoxDictOperator.Text= m_munit.Operator;
                this.textBoxDictRemark.Text = m_munit.Comment;

                Credentials cred = RepoHelper.Repo.GetCredentials(m_munit.Id, Credentials.Type.Municipality);
                this.textBoxDictLogin.Text = cred != null ? cred.Login : string.Empty;
                this.textBoxDictPassword.Text = cred != null ? cred.Password : string.Empty;
                this.textBoxDictPasswordRepeated.Text = cred != null ? cred.Password : string.Empty;
            }
            get
            {
                return m_munit;
            }
        }

        public Municipality Save()
        {
            m_munit.Name = this.textBoxDictMunitName.Text.Trim();
            m_munit.Operator = this.textBoxDictOperator.Text.Trim();
            m_munit.Comment = this.textBoxDictRemark.Text.Trim();

            RepoHelper.Repo.Save(m_munit);

            if (!string.IsNullOrEmpty(this.textBoxDictLogin.Text.Trim()))
            {
                Credentials cred = RepoHelper.Repo.GetCredentials(m_munit.Id, Credentials.Type.Municipality);
                if (cred == null)
                {
                    cred = new Credentials();
                    cred.ReferenceID = m_munit.Id;
                    cred.LoginType = Credentials.Type.Municipality;
                }
                cred.Login = this.textBoxDictLogin.Text.Trim();
                cred.Password = this.textBoxDictPassword.Text.Trim();
                RepoHelper.Repo.Save(cred);
            }

            this.labelError.Text = string.Empty;
            return m_munit;
        }

        public bool CanSave()
        {
            string munitName = this.textBoxDictMunitName.Text.Trim();
            bool isEduExist = (RepoHelper.Repo.GetEduOrgByName(munitName) != null && munitName != m_munit.Name);
            if (isEduExist)
            {
                this.labelError.Text = "ОУ с таким именем уже существует";
                return false;
            }
            bool isFieldsOk = !string.IsNullOrEmpty(munitName);
            if (!isFieldsOk)
            {
                this.labelError.Text = "Проверьте все ли поля заполнены";
                return false;
            }
            string login = this.textBoxDictLogin.Text.Trim();
            string password = this.textBoxDictPassword.Text.Trim();
            if (!string.IsNullOrEmpty(login))
            {
                Credentials cred = RepoHelper.Repo.GetCredentials(m_munit.Id, Credentials.Type.Municipality);
                Credentials cred_dub = RepoHelper.Repo.GetCredentials(login);
                bool isCredentialsExist = cred == null ? cred_dub != null :
                    cred_dub != null ? (cred.ReferenceID != cred_dub.ReferenceID || cred.LoginType != cred_dub.LoginType) : false;
                if (isCredentialsExist)
                {
                    this.labelError.Text = "Такой логин уже существует";
                    return false;
                }
                if (string.IsNullOrEmpty(password))
                {
                    this.labelError.Text = "Пароль не может быть пустым";
                    return false;
                }
                if (password != this.textBoxDictPasswordRepeated.Text.Trim())
                {
                    this.labelError.Text = "Пароли не совпадают";
                    return false;
                }
            }
            return true;
        }

        private void buttonOk_Click(object sender, EventArgs e)
        {
            if (this.CanSave())
            {
                Municipality munit = this.Save();
                
                this.ParentForm.Close();
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            m_munitControl.CancelNew();
            if (this.ParentForm != null)
                this.ParentForm.Close();
        }
    }
}
